package com.teradata.dashboard.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.IBinder;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.teradata.dashboard.DashboardApplication;
import com.teradata.dashboard.R;
import com.teradata.dashboard.constant.DashboardConstant;
import com.teradata.dashboard.service.KpiDataService;
import com.teradata.dashboard.ui.fragment.AlertFragment;
import com.teradata.dashboard.ui.fragment.KpiFragment;
import com.teradata.dashboard.ui.fragment.OrderFragment;
import com.teradata.dashboard.ui.fragment.ProfileFragment;
import com.teradata.dashboard.ui.fragment.SettingFragment;
import com.teradata.dashboard.utils.HttpUtil;


public class MainActivity extends Activity implements OnClickListener  {

	/** 
     * 用于展示消息的Fragment 
     */  
    private KpiFragment kpiFragment;  
  
    /** 
     * 用于展示联系人的Fragment 
     */  
    private OrderFragment orderFragment;  
  
    /** 
     * 用于展示动态的Fragment 
     */  
    private AlertFragment alertFragment;  
  
    /** 
     * 用于展示个人信息的Fragment 
     */  
    private ProfileFragment profileFragment;  
    
    /** 
     * 消息界面布局 
     */  
    private View kpiLayout;  
  
    /** 
     * 联系人界面布局 
     */  
    private View orderLayout;  
  
    /** 
     * 动态界面布局 
     */  
    private View alertLayout;  
  
    /** 
     * 个人信息界面布局 
     */  
    private View profileLayout;
    
    
    
    /** 
     * 用于对Fragment进行管理 
     */  
    private FragmentManager fragmentManager;  
   
    private int backTimes=0;
    
    private KpiDataService.KpiDataBinder kpiDataBinder ;
    
    
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.activity_main);  
        
        //System.out.println(DashboardApplication.app.getUsername());
        initService();
        DashboardApplication.app.intiCookie();
   
        
        // 初始化布局元素  
        initViews();
        fragmentManager = getFragmentManager();  
        // 第一次启动时选中第0个tab  
        setTabSelection(0);  

    }  
    
    
       
    public KpiDataService.KpiDataBinder getKpiDataBinder() {
		return kpiDataBinder;
	}


	private void initService() {
    	
    /*	Intent intent=new Intent(this,KpiDataService.class);
    	ServiceConnection conn=new ServiceConnection(){		  
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				kpiDataBinder=(KpiDataService.KpiDataBinder) service;
				System.out.println("onServiceConnected:"+name+" ;time:"+kpiDataBinder.getLastUpdateTime());
				
			}
			@Override
			public void onServiceDisconnected(ComponentName name) {
				 System.out.println("onServiceDisconnected:"+name);
				
			}  
	   };
		bindService(intent,conn,Context.BIND_AUTO_CREATE);
		*/
		/*while (kpiDataBinder==null) {
			try{
				System.out.println(this.getClass().getName()+"waiting for bind...");
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}*/
		//startService(intent);
		
	}


	/** 
     * 在这里获取到每个需要用到的控件的实例，并给它们设置好必要的点击事件。 
     */  
    private void initViews() {  
        kpiLayout = findViewById(R.id.kpi_layout);  
        orderLayout = findViewById(R.id.order_layout);  
        alertLayout = findViewById(R.id.alert_layout);  
        profileLayout = findViewById(R.id.profile_layout);  
        
        kpiLayout.setOnClickListener(this);  
        orderLayout.setOnClickListener(this);  
        alertLayout.setOnClickListener(this);  
        profileLayout.setOnClickListener(this);  
        
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "fonts/fontawesome-webfont.ttf");
        TextView textview = (TextView)findViewById(R.id.kpi_i);
        textview.setTypeface(iconfont);
        textview = (TextView)findViewById(R.id.order_i);
        textview.setTypeface(iconfont);
        textview = (TextView)findViewById(R.id.alert_i);
        textview.setTypeface(iconfont);
        textview = (TextView)findViewById(R.id.profile_i);
        textview.setTypeface(iconfont);
      
    }  
    
    @Override  
    public void onClick(View v) {  
        switch (v.getId()) {  
        case R.id.kpi_layout:  
            // 当点击了消息tab时，选中第1个tab  
            setTabSelection(0);  
            break;  
        case R.id.order_layout:  
            // 当点击了联系人tab时，选中第2个tab  
            setTabSelection(1);  
            break;  
        case R.id.alert_layout:  
            // 当点击了动态tab时，选中第3个tab  
            setTabSelection(2);  
            break;  
        case R.id.profile_layout:  
            // 当点击了设置tab时，选中第4个tab  
            setTabSelection(3);  
            break;  
        default:  
            break;  
        }  
    }  
    
    /** 
     * 根据传入的index参数来设置选中的tab页。 
     *  
     * @param index 
     *            每个tab页对应的下标。0表示指标，1表示订阅，2表示预警，3表示设置。 
     */  
    
	private void setTabSelection(int index) {  
        // 每次选中之前先清楚掉上次的选中状态  
        clearSelection();  
        // 开启一个Fragment事务  
        FragmentTransaction transaction = fragmentManager.beginTransaction();  
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况  
        hideFragments(transaction);  
        Toast.makeText(MainActivity.this, ""+index, Toast.LENGTH_SHORT).show();
        switch (index) {  
        case 0:  
            // 当点击了消息tab时，改变控件的图片和文字颜色 
            if (kpiFragment == null) { 
                // 如果kpiFragment为空，则创建一个并添加到界面上  
            	kpiFragment = new KpiFragment();  
                transaction.add(R.id.content, kpiFragment);  
            } else {  
                // 如果kpiFragment不为空，则直接将它显示出来  
                transaction.show(kpiFragment);  
            }  
            
            ((TextView)findViewById(R.id.kpi_i)).setTextColor(android.graphics.Color.BLUE);
            ((TextView)findViewById(R.id.acbar_kpi_text)).setTextColor(android.graphics.Color.BLUE);
            break;  
        case 1:  
            // 当点击了联系人tab时，改变控件的图片和文字颜色  
          /*  contactsImage.setImageResource(R.drawable.contacts_selected);  
            contactsText.setTextColor(Color.WHITE);  */
            if (orderFragment == null) {  
                // 如果orderFragment为空，则创建一个并添加到界面上  
                orderFragment = new OrderFragment();  
                transaction.add(R.id.content, orderFragment);  
            } else {  
                // 如果orderFragment不为空，则直接将它显示出来  
                transaction.show(orderFragment);  
            }  
            ((TextView)findViewById(R.id.order_i)).setTextColor(android.graphics.Color.BLUE);
            ((TextView)findViewById(R.id.acbar_order_text)).setTextColor(android.graphics.Color.BLUE);
            break;  
        case 2:  
            // 当点击了动态tab时，改变控件的图片和文字颜色  
           /* newsImage.setImageResource(R.drawable.news_selected);  
            newsText.setTextColor(Color.WHITE);  */
            if (alertFragment == null) {  
                // 如果alertFragment为空，则创建一个并添加到界面上  
                alertFragment = new AlertFragment();  
                transaction.add(R.id.content, alertFragment);  
            } else {  
                // 如果alertFragment不为空，则直接将它显示出来  
                transaction.show(alertFragment);  
            }  
            ((TextView)findViewById(R.id.alert_i)).setTextColor(android.graphics.Color.BLUE);
            ((TextView)findViewById(R.id.acbar_alert_text)).setTextColor(android.graphics.Color.BLUE);
            break;  
        case 3:  
        default:  
            // 当点击了设置tab时，改变控件的图片和文字颜色  
           /* settingImage.setImageResource(R.drawable.setting_selected);  
            settingText.setTextColor(Color.WHITE);  */
            if (profileFragment == null) {  
                // 如果SettingFragment为空，则创建一个并添加到界面上  
            	profileFragment = new ProfileFragment();  
                transaction.add(R.id.content, profileFragment);  
            } else {  
                // 如果SettingFragment不为空，则直接将它显示出来  
                transaction.show(profileFragment);  
            }  
          
            ((TextView)findViewById(R.id.profile_i)).setTextColor(android.graphics.Color.BLUE);
            ((TextView)findViewById(R.id.acbar_profile_text)).setTextColor(android.graphics.Color.BLUE);
            break;  
        }  
        transaction.commit();  
    }  
    
    /** 
     * 清除掉所有的选中状态。 
     */  
    private void clearSelection() {  
    	((TextView)findViewById(R.id.kpi_i)).setTextColor(Color.parseColor("#82858b"));
    	((TextView)findViewById(R.id.acbar_kpi_text)).setTextColor(Color.parseColor("#82858b"));
    	((TextView)findViewById(R.id.order_i)).setTextColor(Color.parseColor("#82858b"));
    	((TextView)findViewById(R.id.acbar_order_text)).setTextColor(Color.parseColor("#82858b"));
    	((TextView)findViewById(R.id.alert_i)).setTextColor(Color.parseColor("#82858b"));
    	((TextView)findViewById(R.id.acbar_alert_text)).setTextColor(Color.parseColor("#82858b"));
    	((TextView)findViewById(R.id.profile_i)).setTextColor(Color.parseColor("#82858b"));
    	((TextView)findViewById(R.id.acbar_profile_text)).setTextColor(Color.parseColor("#82858b"));
    	
    	getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    }  
  
    /** 
     * 将所有的Fragment都置为隐藏状态。 
     *  
     * @param transaction 
     *            用于对Fragment执行操作的事务 
     */  
   
	private void hideFragments(FragmentTransaction transaction) {  
        if (kpiFragment != null) {  
            transaction.hide(kpiFragment);  
        }  
        if (orderFragment != null) {  
            transaction.hide(orderFragment);  
        }  
        if (alertFragment != null) {  
            transaction.hide(alertFragment);  
        }  
        if (profileFragment != null) {  
            transaction.hide(profileFragment);  
        }  
    }  
    
    
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
	    menu.add(0,1,1,R.string.exit);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==1){
			finish();
			System.exit(0);
		}
		
		return super.onOptionsItemSelected(item);
	}
    
	  @Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub

			if (keyCode == KeyEvent.KEYCODE_BACK) {
				backTimes++;
				if(backTimes==1){
					Toast.makeText(MainActivity.this, R.string.exitNextTime, Toast.LENGTH_SHORT).show();
					return true;
				}else if(backTimes==2){
					AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
					builder.setMessage(R.string.exitDialog)
							.setCancelable(false)
							.setPositiveButton(R.string.ok,
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,int id) {
											finish();
											System.exit(0);
										}
									})
							.setNegativeButton(R.string.cancel,
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,int id) {
											dialog.cancel();
										}
									});
					AlertDialog alert = builder.create();
					alert.show();
					return true;
				}			
			}
			return super.onKeyDown(keyCode, event);
		}
	  
	  /**
	  * 回调接口
	  * @author zhaoxin5
	  *
	  */
	  public interface MyTouchListener
	  {
	          public void onTouchEvent(MotionEvent event);
	  }

	  /*
	  * 保存MyTouchListener接口的列表
	  */
	  private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<MainActivity.MyTouchListener>();

	  /**
	  * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
	  * @param listener
	  */
	  public void registerMyTouchListener(MyTouchListener listener)
	  {
	          myTouchListeners.add( listener );
	  }

	  /**
	  * 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法
	  * @param listener
	  */
	  public void unRegisterMyTouchListener(MyTouchListener listener)
	  {
	          myTouchListeners.remove( listener );
	  }

	  /**
	  * 分发触摸事件给所有注册了MyTouchListener的接口
	  */
	  @Override
	  public boolean dispatchTouchEvent(MotionEvent ev) {
	          // TODO Auto-generated method stub 
	          for (MyTouchListener listener : myTouchListeners) {
	                         listener.onTouchEvent(ev);
	          }
	          return super.dispatchTouchEvent(ev);
	  }
}
